import {
	login,
	getLoginUser,
	updateNeetPushService
} from '@/apis/account.js'
import storage from '@/utils/storage'
import languageManager from '@/utils/language'

import { updateTabBarLanguage } from '@/utils/tabbar-i18n.js'

import Vue from 'vue'
const SET_TOKEN = 'SET_TOKEN'
const SET_CURRENT_USER = 'SET_CURRENT_USER'
const UPDATE_LOGIN_USER = 'UPDATE_LOGIN_USER'

const STORAGE_USER_TOKEN = 'STORAGE_USER_TOKEN'
const STORAGE_CURRENT_USER = 'STORAGE_CURRENT_USER'

const CURRENT_TIME_TYPE = 'CURRENT_TIME_TYPE'
const CURRENT_LANGUAGE = 'language'

export default {
	state: {
		currentUser: storage.get(STORAGE_CURRENT_USER),
		tokenInfo: storage.get(STORAGE_USER_TOKEN),
		currentTimeType: storage.get(CURRENT_TIME_TYPE),
		language: storage.get(CURRENT_LANGUAGE)
	},
	getters: {
		currentUser: state => state.currentUser,
		tokenInfo: state => state.tokenInfo,
		isLogin: state => !!(state.currentUser && state.tokenInfo),
		currentTimeType: state => state.currentTimeType,
		language: state => state.language,
	},
	actions: {
		CheckAccountLogin ({ commit, dispatch }, data) {
			return login(data)
		},
		UpdateNeetPushService ({ commit }, data) {
			return updateNeetPushService(data).then(rs => {
				commit(UPDATE_LOGIN_USER, {
					needService: data.flag
				})
			})
		},
		SetUserLogin ({ commit }, data) {
			if (!data || !data.accessToken) {
				return Promise.reject('不是合法的用户数据')
			}
			const { accessToken, ...user } = data
			commit(SET_TOKEN, accessToken)
			return getLoginUser().then(rs => {
				console.log("123========================",rs)
				storage.set(CURRENT_TIME_TYPE, rs?rs.currentTimeType:'')
				if(rs.currentTimeType===1){
					languageManager.setLocale('en');					// 可以将语言设置保存到本地存储
					storage.set(CURRENT_LANGUAGE,'en' )
				}else {
					languageManager.setLocale('zh');					// 可以将语言设置保存到本地存储
					storage.set(CURRENT_LANGUAGE, 'zh')
				}
				updateTabBarLanguage()
				commit(SET_CURRENT_USER, rs)
			})
		},
		SetUserLogout ({ commit }) {
			commit(SET_TOKEN, null)
			commit(SET_CURRENT_USER, null)
		},
		UpdateLoginUser ({ commit }, data) {
			commit(UPDATE_LOGIN_USER, data)
		}
	},
	mutations: {
		[SET_TOKEN] (state, token) {
			storage.set(STORAGE_USER_TOKEN, token)
			state.tokenInfo = token || null
		},
		[SET_CURRENT_USER] (state, data) {
			storage.set(STORAGE_CURRENT_USER, data)
			state.currentUser = data || null
		},
		[UPDATE_LOGIN_USER] (state, data) {
			if (!data) {
				return
			}
			const nameAlias = {
				name: 'userName',
				companyId: 'ownCompanyId',
				companyName: 'ownCompanyName'
			}
			Object.keys(data).forEach(k => {
				const updateKey = nameAlias[k] || k
				state.currentUser[updateKey] = data[k]
			})
			storage.set(STORAGE_CURRENT_USER, state.currentUser)
		}
	}
}
